/* eslint-disable eqeqeq */
/**
 * @description  银行间质押式回购基础信息（回购指令）
 * @author shenhong
 */
import { Form } from '@ant-design/compatible';

import '@ant-design/compatible/assets/index.css';
import { strip } from 'number-precision';

import { message } from 'antd';
import { connect } from 'dva';
import debounce from 'lodash/debounce';
import moment from 'moment';
import PropTypes from 'prop-types';
import React, { PureComponent } from 'react';

import Buyout from './constant';
import style from './index.less';

import { DATA_ENTRY, FormGroup, TradingTypeC } from '../../../../comps';
import { isZiGuanEvir, calculateFee } from '../../../../utils/commonFunc';
import buybackCodeData from '../../../../utils/enumeratedValues/InterBank';
import investmentTypeData from '../../../../utils/enumeratedValues/investmentType';
import { formSelectData } from '../../../../utils/utils';

@Form.create()
class BasicInfo extends PureComponent {
  static defaultProps = {
    onRef: () => {},
    portfolioOnChange: () => {},
    directOnChange: () => {},
    trusteeOnChange: () => {},
  };

  constructor() {
    super();
    this.state = {
      buyBackMoney: undefined, // 回购金额
      buyBackRate: undefined, // 回购利率
      occupationDays: undefined, // 实际占款天数
      isDisabled: false, // 详情和交收时表单全部置灰
      isCanOrder: true, // 是否可以下达 默认可以下达
      isZiGuan: false,
      feeData: {
        // 费用自动计算条件
        exchangecode: '113',
        sectype: 'hg',
        sectypeii: 'zyshg',
        orderside: undefined,
        timeLimit: undefined,
        pledgedbondsamount: undefined,
        price: undefined,
      },
      firstSettlementDate: moment(),
    };
  }

  componentDidMount() {
    const { dispatch, type } = this.props;
    this.props.onRef(this);
    const temp = isZiGuanEvir();
    const isZiGuan = !!temp; // 判断该页面是在资管被引入的，还是maat
    // eslint-disable-next-line react/no-did-mount-set-state
    this.setState({
      isZiGuan,
    });
    if (type == 3 || type == 4) {
      // eslint-disable-next-line react/no-did-mount-set-state
      this.setState({
        isDisabled: true,
      });
    }
    const {
      globalM: {
        dataDictionary: { BANK_SETTLEMENT_METHOD = [] },
      },
    } = this.props;
    dispatch({
      type: 'interBankBasicInfoM/save',
      payload: {
        getSpeed: formSelectData(BANK_SETTLEMENT_METHOD),
      },
    });
    if (type == '12') {
      // eslint-disable-next-line react/no-did-mount-set-state
      this.setState({ feeData: { ...this.state.feeData, groupId: undefined } });
    } else {
      // eslint-disable-next-line react/no-did-mount-set-state
      this.setState({ feeData: { ...this.state.feeData, productId: undefined, portfolioid: undefined } });
    }
    this.repurchaseDaysOnChange = debounce(this.repurchaseDaysOnChange, 500);
  }

  // 费用自动计算
  changeFee = (type, data) => {
    const {
      form: { setFieldsValue },
    } = this.formGroupThis.props;
    if (this.props.type == 3 || this.props.type == 4) return; // 详情不计算
    setTimeout(() => {
      if (data == undefined) {
        setFieldsValue({ fee: undefined });
        if (type == 'productId') {
          this.setState({ feeData: { ...this.state.feeData, productId: undefined, portfolioid: undefined } });
        } else {
          this.setState({ feeData: { ...this.state.feeData, [type]: undefined } });
        }
      } else {
        this.setState({ feeData: { ...this.state.feeData, [type]: data } }, () => {
          const fee = calculateFee(this.state.feeData, !!(this.props.type == 10 || this.props.type == 12));
          fee.then((r) => {
            setFieldsValue({ fee: r });
          });
        });
      }
    }, 100);
  };

  // 质押券总计改变计算回购金额
  changeAccount = (e) => {
    if (this.props.type == '3' || this.props.type == '4') {
      return;
    }
    const {
      form: { setFieldsValue },
    } = this.formGroupThis.props;
    if (e) {
      setFieldsValue({
        repurchaseAmount: e,
      });
      this.setState({ buyBackMoney: e }, () => this.setBuyBackRate());
    } else {
      setFieldsValue({
        repurchaseAmount: '',
      });
      this.setState({ buyBackMoney: '' }, () => this.setBuyBackRate());
    }
  };

  // 设置回购利率
  setBuyBackRate = () => {
    const { buyBackMoney, buyBackRate, occupationDays } = this.state;
    const {
      form: { setFieldsValue },
    } = this.formGroupThis.props;
    // 回购金额不为空并且回购利率不为空时计算到期结算金额
    if (buyBackMoney !== undefined && buyBackRate !== undefined && occupationDays !== undefined) {
      // eslint-disable-next-line no-mixed-operators
      const num = buyBackMoney * (buyBackRate * 0.01 * (occupationDays / 365)) + buyBackMoney;
      setFieldsValue({
        expireAmount: Number(num?.toFixed(2)),
      });
    }
  };

  // 根据而清算速度获取首期结算日期
  getNowDate = (e) => {
    const {
      form: { setFieldsValue },
    } = this.formGroupThis.props;
    const date = e == '1' ? moment() : e == '2' ? moment().add(1, 'day') : moment();
    this.setState({ firstSettlementDate: date });
    setFieldsValue({ firstSettlementDate: date });
    this.repurchaseDaysOnChange();
  };

  // 组合与交易方向切换时清空持仓信息
  changePositionData = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'interBankBasicInfoM/save',
      payload: { posisionData: { columns: [], dataSource: [] } },
    });
  };

  // 成功&取消时重置表单
  setForm = () => {
    const { form } = this.formGroupThis.props;
    form.resetFields();
    this.props.directOnChange(undefined);
    this.props.portfolioOnChange(undefined);
    this.props.trusteeOnChange(undefined);
    this.setState({
      isCanOrder: true,
      firstSettlementDate: moment(),
    });
  };

  // chek
  checkPortfolio = (value) => {
    let val;
    if (value) val = value.key;
    if (val && this.props.type == 1) {
      // 新增指令时 需要判断该组合是否进行了指令配置
      this.props.dispatch({
        type: 'isAccountConfiguredM/queryIsAccountConfigured',
        payload: {
          portId: val,
        },
        callback: (data) => {
          if (data.result) {
            this.setState({
              isCanOrder: true,
            });
          } else {
            this.setState({
              isCanOrder: false,
            });
            message.warning(data.msg);
          }
        },
      });
    } else if (!val && this.props.type == 1) {
      this.setState({
        isCanOrder: true,
      });
    }
  };

  // 交易方向改变清空回购金额
  changeOrderSide = () => {
    this.props.form.setFieldsValue({ repurchaseAmount: '' });
  };

  // 首期/到期结算日改变
  settlementDateChange = () => {
    const {
      form: { setFieldsValue, getFieldValue },
    } = this.formGroupThis.props;
    setTimeout(() => {
      if (getFieldValue('firstSettlementDate') && getFieldValue('settlementDate')) {
        this.props.dispatch({
          type: 'interBankBasicInfoM/getOccupationDays',
          payload: {
            startDate: getFieldValue('firstSettlementDate').format('YYYY-MM-DD'),
            endDate: getFieldValue('settlementDate').format('YYYY-MM-DD'),
          },
          callback: (res) => {
            if (res) {
              this.setState(
                {
                  occupationDays: res, // 实际占款天数
                },
                this.setBuyBackRate,
              ); // 实际占款天数改变，到期结算金额
              setFieldsValue({
                occupationDays: res, // 实际占款天数
              });
            }
          },
        });
      }
    }, 0);
  };
  // 回购天数改变计算到期结算日
  // eslint-disable-next-line lines-between-class-members
  repurchaseDaysOnChange = () => {
    const {
      form: { setFieldsValue, getFieldValue },
    } = this.formGroupThis.props;
    setTimeout(() => {
      if (getFieldValue('repurchaseDays') && getFieldValue('firstSettlementDate')) {
        this.setState({ firstSettlementDate: getFieldValue('firstSettlementDate') });
        this.props.dispatch({
          type: 'exchangeAgreement/calculation',
          payload: {
            repurchaseDays: getFieldValue('repurchaseDays'),
            firstSettlemenDate: getFieldValue('firstSettlementDate').format('YYYY-MM-DD'),
          },
          callback: (data) => {
            if (data) {
              setFieldsValue(
                {
                  settlementDate: moment(data.settlementDate),
                },
                () => {
                  this.settlementDateChange();
                },
              );
            }
          },
        });
      } else {
        setFieldsValue({
          settlementDate: null,
        });
      }
    }, 0);
  };

  // 表单渲染
  formContent = () => {
    const {
      interBankBasicInfoM: { getSpeed },
      infoData,
      type,
      listId,
    } = this.props;
    const { isZiGuan, firstSettlementDate } = this.state;
    const isDisabled = !!(type == '3' || type == '4');
    const jg = [
      { title: '中债', value: '309904' },
      { title: '上清', value: '549888' },
    ];
    const direct = [
      { title: '融券回购', value: '1' },
      { title: '融资回购', value: '2' },
    ];
    const qslx = [
      { title: '净额清算', value: '6' },
      { title: '全额清算', value: '13' },
    ];
    const qssd = [
      { title: 'T+0', value: '1' },
      { title: 'T+1', value: '2' },
    ];

    const tradeNum = type == 3 || type == 4 ? `trade${infoData.type}` : undefined;
    return (
      <FormGroup
        dataSource={[
          type == 10
            ? {
                dataIndex: 'listId',
                type: DATA_ENTRY.SERIESPRODUCTGROUP,
                rules: [{ required: true, message: '请选择系列产品!' }],
                disabled: true,
                initialValue: listId,
                onChange: (e) => {
                  this.props.seriesProductsOnChange(e?.value);
                }, // 向外抛处系列产品id
                span: 12,
                controlLabelSpan: 8,
              }
            : type == 12
            ? {
                dataIndex: 'productGroupId',
                type: DATA_ENTRY.PRODUCTGROUP,
                rules: [{ required: true, message: '请选择产品组!' }],
                onChange: (e) => {
                  this.props.productGroupOnChange(e || undefined); // 向外抛处组合id
                  this.changeFee('groupId', e?.key);
                },
                span: 6,
                controlLabelSpan: 8,
                tradeModel: type == 12 ? ['BOOKKEEPING_MODE', 'COMMAND_MODE'] : undefined, // 不包含估值解析和估值对接的产品
              }
            : {
                dataIndex: ['productId', 'portfolioId'],
                type: DATA_ENTRY.PRODUCTGROUPSEP,
                multipleGroup: false,
                initialValue: type == '3' || type == '4' ? [infoData[tradeNum].productId, infoData[tradeNum].portfolioId] : undefined,
                disabled: isDisabled,
                rules: [[{ required: true, message: '请选择产品!' }], [{ required: true, message: '请选择组合!' }]],
                groupOnChange: (e) => {
                  this.props.portfolioOnChange(e); // 向外抛处组合id(本组件内使用)
                  this.props.portfolioCode(e ? e.info.portfolioCode : undefined); // 向外抛出组合code
                  this.changeFee('portfolioid', e ? e.key : undefined);
                  this.changePositionData(); // 清空持仓信息
                  this.checkPortfolio(e); // 校验是否可以下达指令
                },
                productOnChange: (e) => {
                  this.props.productCode(e ? e.info.portfolioCode : undefined); // 向外抛出产品code
                  this.changeFee('productId', e ? e.key : undefined);
                },
                authority: 'write', // 可写权限
                exist: 1,
                span: 12,
                controlLabelSpan: 8,
                tradeModel: type == 1 || type == 2 ? ['BOOKKEEPING_MODE', 'COMMAND_MODE'] : undefined, // 不包含估值解析和估值对接的产品
              },
          {
            title: '托管机构',
            dataIndex: 'clientCode',
            type: DATA_ENTRY.SELECT,
            dataSource: jg,
            rules: [{ required: true, message: '请选择托管机构!' }],
            multiple: false,
            disabled: isDisabled,
            initialValue: type == '3' || type == '4' ? infoData[tradeNum].clientCode : '',
            onChange: (e) => {
              this.props.trusteeOnChange(e);
              this.changePositionData(); // 清空持仓信息
            },
            placeholder: '请选择',
            span: 6,
            controlLabelSpan: 8,
            onRef: (ref) => (this.formGroupThis = ref),
          },
          {
            title: '交易方向', // 交易方向
            dataIndex: 'orderSide',
            type: DATA_ENTRY.SELECT,
            dataSource: direct,
            rules: [{ required: true, message: '请选择交易方向!' }],
            multiple: false,
            disabled: isDisabled,
            initialValue: type == '3' || type == '4' ? infoData[tradeNum].orderSide : '',
            placeholder: '请选择',
            onChange: (e) => {
              this.props.directOnChange(e);
              this.changeFee('orderside', e || undefined);
              this.changeOrderSide;
            },
            span: 6,
            controlLabelSpan: 8,
          },
          {
            title: '回购代码',
            dataIndex: 'buybackCode',
            placeholder: '请输入',
            type: DATA_ENTRY.SELECT,
            initialValue: type == '3' || type == '4' ? infoData[tradeNum].buybackCode : undefined,
            dataSource: [...buybackCodeData, ...Buyout],
            rules: [{ required: true, message: '请选择回购代码' }],
            span: 6,
            disabled: isDisabled,
            controlLabelSpan: 8,
            onChange: (e) => {
              this.props.changeBuybackCode(e);
            },
          },
          {
            title: '回购期限',
            dataIndex: 'repurchaseDays',
            placeholder: '请输入',
            type: DATA_ENTRY.INPUTNUMBER,
            initialValue: type == '3' || type == '4' ? infoData[tradeNum].hgSpan : '',
            precision: 0,
            disabled: isDisabled,
            onChange: this.repurchaseDaysOnChange,
            unit: '天',
            span: 6,
            controlLabelSpan: 8,
          },
          {
            title: '清算速度',
            dataIndex: 'settlementSpeed',
            type: DATA_ENTRY.SELECT,
            dataSource: qssd,
            disabled: isDisabled,
            initialValue: type == '3' || type == '4' ? infoData[tradeNum].settlementSpeed : '1',
            rules: [{ required: true, message: '请选择清算速度!' }],
            multiple: false,
            placeholder: '请选择',
            onChange: this.getNowDate,
            span: 6,
            controlLabelSpan: 8,
          },
          {
            title: '首期结算日期',
            type: DATA_ENTRY.SINGLEDATE,
            dataIndex: 'firstSettlementDate',
            initialValue: type == '3' || type == '4' ? moment(infoData[tradeNum].firstSettlementDate) : firstSettlementDate,
            rules: [{ required: true, message: '请选择首期结算日期' }],
            span: 6,
            controlLabelSpan: 8,
            disabled: isDisabled,
            disableBegin: moment().subtract(1, 'day'),
            onChange: this.repurchaseDaysOnChange,
          },
          {
            title: '到期结算日期',
            dataIndex: 'settlementDate',
            type: DATA_ENTRY.SINGLEDATE,
            initialValue: type == '3' || type == '4' ? moment(infoData[tradeNum].settlementDate) : null,
            rules: [{ required: true, message: '请选择到期结算日期' }],
            onChange: this.settlementDateChange,
            disableBegin: firstSettlementDate || undefined,
            disabled: isDisabled,
            span: 6,
            controlLabelSpan: 8,
          },
          {
            title: '回购金额',
            dataIndex: 'repurchaseAmount',
            type: DATA_ENTRY.INPUTNUMBER,
            placeholder: '请输入',
            precision: 2,
            min: 0,
            max: 999999999999,
            disabled: isDisabled,
            initialValue: type == '3' || type == '4' ? infoData[tradeNum].repurchaseAmount : '',
            splitStyle: true,
            onChange: (e) => {
              if (e !== undefined && e !== null) {
                this.setState(
                  {
                    buyBackMoney: e,
                  },
                  () => this.setBuyBackRate(),
                );
              }
            },
            rules: [{ required: true, message: `请输入回购金额` }],
            unit: '元',
            span: 6,
            controlLabelSpan: 8,
          },
          {
            title: '回购利率',
            dataIndex: 'repoRate',
            placeholder: '请输入',
            type: DATA_ENTRY.INPUTNUMBER,
            precision: 2,
            min: 0,
            splitStyle: true,
            max: 100,
            disabled: isDisabled,
            onChange: (e) => {
              if (e !== undefined && e !== null) {
                this.setState(
                  {
                    buyBackRate: e,
                  },
                  () => {
                    this.setBuyBackRate();
                  },
                );
              }
            },
            initialValue: type == '3' || type == '4' ? infoData[tradeNum].repoRate : '',
            rules: [{ required: true, message: `请输入回购利率` }],
            unit: '%',
            span: 6,
            controlLabelSpan: 8,
          },
          {
            title: '实际占款天数',
            dataIndex: 'occupationDays',
            placeholder: '请输入',
            type: DATA_ENTRY.INPUTNUMBER,
            initialValue: type == '3' || type == '4' ? infoData[tradeNum].occupationDays : '',
            disabled: true,
            precision: 0,
            unit: '天',
            span: 6,
            controlLabelSpan: 8,
          },
          {
            title: '到期结算金额',
            dataIndex: 'expireAmount',
            // eslint-disable-next-line max-lines
            placeholder: '请输入',
            type: DATA_ENTRY.INPUTNUMBER,
            precision: 2,
            splitStyle: true,
            initialValue: type == '3' || type == '4' ? Number(infoData[tradeNum].expireAmount?.toFixed(2)) : '',
            disabled: true,
            unit: '元',
            span: 6,
            controlLabelSpan: 8,
          },
          {
            // 交易对手
            dataIndex: 'counterparty',
            type: DATA_ENTRY.TRADINGCOMPANY,
            initialValue: type == '3' || type == '4' ? infoData[tradeNum].counterparty : '',
            multiple: false,
            disabled: isDisabled,
            placeholder: '请选择',
            rules: [{ required: true, message: '请输入交易对手!' }],
            span: 6,
            controlLabelSpan: 8,
            scenesType: type, // 组件场景类型，用于详情时根据ID回填值
          },
          {
            title: '对手交易员',
            dataIndex: 'counterpartyPer',
            type: DATA_ENTRY.INPUT,
            placeholder: '请输入',
            initialValue: type == '3' || type == '4' ? infoData[tradeNum].counterpartyPer : '',
            disabled: isDisabled,
            span: 6,
            controlLabelSpan: 8,
          },
          {
            title: '清算类型',
            dataIndex: 'clearingMethod',
            type: DATA_ENTRY.SELECT,
            dataSource: qslx,
            rules: [{ required: true, message: '请选择清算类型!' }],
            multiple: false,
            initialValue: type == '3' || type == '4' ? infoData[tradeNum].clearingMethod : '13',
            disabled: isDisabled,
            placeholder: '请选择',
            span: 6,
            controlLabelSpan: 8,
          },
          {
            // 交易类型
            dataIndex: 'orderType',
            type: DATA_ENTRY.TRADINGTYPE,
            rules: [{ required: true, message: '请选择交易类型!' }],
            initialValue: type == '3' || type == '4' ? infoData[tradeNum].orderType : '2',
            multiple: false,
            disabled: true,
            placeholder: '请选择',
            span: 6,
            controlLabelSpan: 8,
          },
          {
            title: '投资类型',
            dataIndex: 'investmentType',
            type: DATA_ENTRY.SELECT,
            initialValue: type == '3' || type == '4' ? infoData[tradeNum].investmentType : undefined,
            disabled: isDisabled,
            dataSource: investmentTypeData,
            allowClear: true,
            rules: [{ required: false, message: '请选择' }],
            span: 6,
            controlLabelSpan: 8,
            hide: type == 10 && isZiGuan,
          },
          {
            title: '首期结算方式',
            dataIndex: 'firstSettlementType',
            type: DATA_ENTRY.SELECT,
            dataSource: getSpeed,
            initialValue: type == '3' || type == '4' ? infoData[tradeNum].firstSettlementType : '0',
            multiple: false,
            disabled: isDisabled,
            placeholder: '请选择',
            span: 6,
            controlLabelSpan: 8,
          },
          {
            title: '到期结算方式',
            dataIndex: 'settlementType',
            type: DATA_ENTRY.SELECT,
            dataSource: getSpeed,
            disabled: isDisabled,
            initialValue: type == '3' || type == '4' ? infoData[tradeNum].settlementType : '0',
            multiple: false,
            placeholder: '请选择',
            span: 6,
            controlLabelSpan: 8,
          },
          {
            // 交易录入 拆分有费用
            title: '费用',
            dataIndex: 'fee',
            placeholder: '请输入',
            disabled: !!(type == '3' || type == '4'),
            unit: '元',
            span: 6,
            controlLabelSpan: 8,
            hide: type != 10 || type != 12,
          },
          {
            dataIndex: 'describe',
            type: DATA_ENTRY.INPUT,
            title: '备注',
            disabled: isDisabled,
            initialValue: type == '3' || type == '4' ? infoData[tradeNum].describe : '',
            placeholder: '请输入',
            showTextArea: true,
            autosize: { minRows: 2, maxRows: 2 },
            span: 24,
            controlLabelSpan: 2,
          },
        ]}
        autoLayout={false}
        rowNumber={4}
      />
    );
  };

  // 获取校验并获取表单的值
  getInfo = () => {
    const {
      form: { validateFields },
    } = this.formGroupThis.props;
    let query = {};
    if (!this.state.isCanOrder && this.props.type == 1) {
      // 在点击“下达”时，若标记指示未配置指令，则提示用户“该组合为配置指令，无法下发指令。
      message.warning(this.props.errorSetMsg);
      return;
    }
    validateFields((err, fieldsValue) => {
      if (!err) {
        query = fieldsValue;
        if (this.props.type != 10 && this.props.type != 12) query.fee = 0; // 费用计算逻辑未完全梳理清楚，后续用户有真正需求时再添加费用计算相关逻辑
      }
    });
    if (JSON.stringify(query) == '{}') {
      query = undefined;
    } else if (query.repurchaseAmount < 0 || query.buyBackRate < 0) {
      message.warning('回购金额、回购利率不得小于0');
      query = undefined;
    }
    return query;
  };

  render() {
    return <div className={style.info}>{this.formContent()}</div>;
  }
}
// props类型
TradingTypeC.propsTypes = {
  type: PropTypes.string, // 类型  (1-指令新增   2-簿记新增    3-详情   4-交收  10-存续管理)
  // eslint-disable-next-line react/forbid-prop-types
  info: PropTypes.object, // 设置表单布局
};
export default connect(({ globalM, interBankBasicInfoM, isAccountConfiguredM, exchangeAgreement }) => ({
  globalM,
  interBankBasicInfoM,
  isAccountConfiguredM,
  errorSetMsg: isAccountConfiguredM.msg,
  exchangeAgreement,
}))(BasicInfo);
